<template>
  <div class="max_kb">
    <iframe
      v-if="url"
      ref="frameRef"
      :src="url"
      frameborder="no"
      scrolling="auto"
      style="width: 100%; height: 100%; background-color: #fff"
      @load="onIframeLoad"
    ></iframe>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserEncrypt } from '@/api/call/maxkb/index'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()

const url = ref(null)
const code = ref(null)
const frameRef = ref(null)

const getCode = async () => {
  const data = await getUserEncrypt()
  if (data) {
    code.value = data
    url.value = `https://ui_maxkb.jzsaas.com/login?key=${Math.random()}`
    // url.value = `http://192.168.0.39:3000/login?key=${Math.random()}`
  }
}

const onIframeLoad = () => {
  if (!frameRef.value) return
  const roles = wsCache.get(CACHE_KEY.USER).roles
  const contains = roles.includes('tenant_admin') || roles.includes('super_admin')
  // 确保iframe完全加载后再发送消息
  setTimeout(() => {
    const iframeWindow = frameRef.value.contentWindow
    const targetOrigin = new URL(url.value).origin
    const message = {
      type: 'init',
      data: {
        token: code.value,
        authorization: getAccessToken(),
        tenantId: getTenantId(),
        userId: useUserStore().getUser.id,
        contains: contains
      }
    }
    iframeWindow.postMessage(message, targetOrigin)
  }, 500)
}

onMounted(() => {
  getCode()
})
</script>

<style lang="scss" scoped>
.max_kb {
  width: 100%;
  flex-grow: 1;
  background-color: #fff;
}
</style>
